package com.purang.web.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.purang.web.config.HttpClientUtilsConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.*;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.Assert;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * http发送工具，该工具对apache httpclient进行了封装<br>
 * 该工具类的初始化由spring容器{@link HttpClientUtilsConfig}<br>
 * 调用{@link #init(HttpClientUtilsConfig.UriConfig, HttpClientUtilsConfig.HttpClientConfig)})}初始化。
 * <p>
 * 使用示范：<br>
 * <code>
 * HttpClientUtils.builder().get().uri("/test").heads(heads).params(params).build().executeHttp();
 * </code>
 *
 * @author Chuan Qin
 * @author Chunyan Li
 * @author Zheming Liu
 * @version 1.0-RELEASE
 * @see {@link com.purang.web.controller.TestController}演示
 * @since 1.0-RELEASE
 */
@Slf4j
public class HttpClientUtils {

    private static HttpClientBuilder httpClientBuilder;

    private static RequestConfig requestConfig;

    private RequestBuilder requestBuilder;

    private HttpClientUtils(RequestBuilder requestBuilder) {
        this.requestBuilder = requestBuilder;
    }

    private static Map<String, String> uriMapping;

    private static String uriPre;

    /**
     * 初始化工具，{@link HttpClientUtilsConfig}中已经初始化
     *
     * @param uriConfig        HttpClient发送目标路径
     * @param httpClientConfig HttpClient配置
     */
    public static void init(HttpClientUtilsConfig.UriConfig uriConfig, HttpClientUtilsConfig.HttpClientConfig httpClientConfig) {
        Assert.notNull(uriConfig, "The init param uriConfig can't be null");
        Assert.notNull(httpClientConfig, "The init param httpClientConfig can't be null");
        if (uriMapping == null) {
            uriMapping = uriConfig.getMap();
        }
        if (uriPre == null) {
            uriPre = httpClientConfig.getScheme() + "://" + httpClientConfig.getHost() + ":" + httpClientConfig.getPort() + "/";
        }
        String maxConnection = httpClientConfig.getMaxConnection();
        String defaultMaxConnection = httpClientConfig.getDefaultMaxPerRout();
        String timeout = httpClientConfig.getTimeout();
        if (requestConfig == null) {
            requestConfig = RequestConfig
                    .custom()
                    .setSocketTimeout(Integer.valueOf(timeout))
                    .setConnectTimeout(Integer.valueOf(timeout))
                    .setConnectionRequestTimeout(Integer.valueOf(timeout))
                    .build();
        }
        if (httpClientBuilder == null) {
            PoolingHttpClientConnectionManager clientConnectionManager = new PoolingHttpClientConnectionManager();
            clientConnectionManager.setMaxTotal(Integer.valueOf(maxConnection));
            clientConnectionManager.setDefaultMaxPerRoute(Integer.valueOf(defaultMaxConnection));
            httpClientBuilder = HttpClients.custom();
            httpClientBuilder.setConnectionManager(clientConnectionManager);
        }
    }

    /**
     * 构造器
     */
    public static HttpClientUtilsBuilder builder() {
        return new HttpClientUtilsBuilder();
    }

    /**
     * 执行对应的http请求
     *
     * @return http请求返回结果
     */
    public JSONObject executeHttp() {
        long start = System.currentTimeMillis();
        log.info("Http send start");
        CloseableHttpClient httpClient = httpClientBuilder.build();
        Assert.notNull(requestBuilder, "Please select a request method first");
        JSONObject result = null;
        try {
            CloseableHttpResponse response = httpClient.execute(requestBuilder.setConfig(requestConfig).build());
            if (response.getStatusLine().getStatusCode() == 200) {
                result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "utf-8"));
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        long end = System.currentTimeMillis();
        log.info("Http send end,cost {}ms", end - start);
        return result;
    }

    public static class HttpClientUtilsBuilder {

        private RequestBuilder requestBuilder;

        private MultipartEntityBuilder entityBuilder;

        /**
         * post请求（有参），Content-Type为application/x-www-form-urlencoded
         *
         * @param params 表单参数
         */
        public HttpClientUtilsBuilder xForm(Map<String, String> params) {
            Assert.notNull(params, "The request params can't be null");
            xForm();
            List<BasicNameValuePair> parameters = params.entrySet().stream().map(a -> new BasicNameValuePair(a.getKey(), a.getValue())).collect(Collectors.toList());
            requestBuilder.setEntity(new UrlEncodedFormEntity(parameters, StandardCharsets.UTF_8));
            return this;
        }

        /**
         * post请求（无参），Content-Type为application/x-www-form-urlencoded
         */
        public HttpClientUtilsBuilder xForm() {
            requestBuilder = RequestBuilder.post();
            log.info("The request method is post,bind Content-Type application/x-www-form-urlencoded");
            return this;
        }

        /**
         * post请求，Content-Type为application/json
         *
         * @param jsonStr 请求体json字符串
         */
        public HttpClientUtilsBuilder body(String jsonStr) {
            Assert.notNull(jsonStr, "Json string can't be null");
            requestBuilder = RequestBuilder.post();
            StringEntity entity = new StringEntity(jsonStr, ContentType.APPLICATION_JSON);
            requestBuilder.setEntity(entity);
            log.info("The request method is post,bind Content-Type application/json");
            return this;
        }

        /**
         * post请求，Content-Type为multipart/form-data
         *
         * @param params 表单参数
         */
        public HttpClientUtilsBuilder multipartForm(Map<String, String> params) {
            Assert.notNull(params, "The request params can't be null");
            requestBuilder = RequestBuilder.post();
            if (entityBuilder == null) {
                entityBuilder = MultipartEntityBuilder.create().setCharset(StandardCharsets.UTF_8);
            }
            for (Map.Entry<String, String> param : params.entrySet()) {
                entityBuilder.addTextBody(param.getKey(), param.getValue(), ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8));
            }
            requestBuilder.setEntity(entityBuilder.build());
            log.info("The request method is post,bind Content-Type multipart/form");
            return this;
        }

        /**
         * post请求，Content-Type为multipart/form-data
         *
         * @param file 上传文件
         */
        public HttpClientUtilsBuilder multipartForm(File file) {
            Assert.notNull(file, "The request file can't be null");
            requestBuilder = RequestBuilder.post();
            if (entityBuilder == null) {
                entityBuilder = MultipartEntityBuilder.create().setCharset(StandardCharsets.UTF_8);
            }
            entityBuilder.addPart("file", new FileBody(file, ContentType.APPLICATION_OCTET_STREAM));
            requestBuilder.setEntity(entityBuilder.build());
            log.info("The request method is post,bind Content-Type multipart/form");
            return this;
        }

        /**
         * get请求（无参）
         */
        public HttpClientUtilsBuilder get() {
            requestBuilder = RequestBuilder.get();
            log.info("The request method is get");
            return this;
        }

        /**
         * get请求（有参）
         *
         * @param params 请求参数
         */
        public HttpClientUtilsBuilder get(Map<String, String> params) {
            Assert.notNull(params, "The request params can't be null");
            get();
            return params(params, false);
        }

        /**
         * get请求（有参）
         *
         * @param params        请求参数
         * @param whetherEncode 是否使用UrlEncoder加密
         */
        public HttpClientUtilsBuilder get(Map<String, String> params, boolean whetherEncode) {
            Assert.notNull(params, "The request params can't be null");
            get();
            return params(params, whetherEncode);
        }

        /**
         * 请求头添加
         *
         * @param heads 请求头
         */
        public HttpClientUtilsBuilder heads(Map<String, String> heads) {
            Assert.notNull(heads, "The request heads can't be null");
            Assert.notNull(requestBuilder, "Please select a request method first");
            for (Map.Entry<String, String> head : heads.entrySet()) {
                requestBuilder.addHeader(head.getKey(), head.getValue());
            }
            return this;
        }

        /**
         * 请求参数添加
         *
         * @param params 请求参数
         */
        private HttpClientUtilsBuilder params(Map<String, String> params, boolean whetherEncode) {
            Assert.notNull(params, "The request params can't be null");
            Assert.notNull(requestBuilder, "Please select a request method first");
            for (Map.Entry<String, String> param : params.entrySet()) {
                if (whetherEncode) {
                    try {
                        requestBuilder.addParameter(param.getKey(), URLEncoder.encode(param.getValue(), "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        log.error(e.getMessage(), e);
                        requestBuilder = null;
                    }
                } else {
                    requestBuilder.addParameter(param.getKey(), param.getValue());
                }
            }
            return this;
        }

        /**
         * 指定请求的uri
         *
         * @param uri 只需提供servlet地址
         */
        public HttpClientUtilsBuilder uri(String uri) {
            Assert.notNull(uri, "The request uri can't be null");
            Assert.notNull(requestBuilder, "Please select a request method first");
            if (uri.startsWith("/")) {
                uri = uri.replaceFirst("/", "");
            }
            uri = uriPre + uri;
            log.info("Request uri {}", uri);
            requestBuilder.setUri(uri);
            return this;
        }

        /**
         * 从{@link #uriMapping}中获得uri
         *
         * @param uriKey uriMapping对应的key
         */
        public HttpClientUtilsBuilder uriFromMap(String uriKey) {
            Assert.notNull(uriKey, "The request uri can't be null");
            Assert.notNull(requestBuilder, "Please select a request method first");
            String uri = uriMapping.get(uriKey);
            Assert.notNull(uri, "The uri is not present");
            if (uri.startsWith("/")) {
                uri = uri.replaceFirst("/", "");
            }
            uri = uriPre + uri;
            log.info("Request uri {}", uri);
            requestBuilder.setUri(uri);
            return this;
        }

        /**
         * 建造HttpSendUtils
         */
        public HttpClientUtils build() {
            Assert.notNull(requestBuilder, "Please select a request method first");
            Assert.notNull(requestBuilder.getUri(), "Please add uri to your request");
            return new HttpClientUtils(requestBuilder);
        }
    }
}
